<template>
  <div class="role-container">
    <div class="box">
      <div class="rc-1">
        <el-button v-permission="'add-role'" type="primary" size="mini" @click="addRole">
          添加角色
        </el-button>
      </div>
      <div class="rc-2">
        <el-table
          :data="roleList"
          style="width: 100%"
        >
          <el-table-column
            prop="name"
            label="角色"
            width="180"
            align="center"
          >
            <!-- 关于template标签：是一个占位符渲染时不会生成dom标签，vue3中插槽v-slot新语法，只能在template标签中使用 -->
            <template v-slot="{row}">
              <div v-if="row.isEdit">
                <el-input v-model="editForm.name" />
              </div>
              <div v-else>
                {{ row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-slot="{row}"
            prop="state"
            label="启用"
            width="180"
            align="center"
          >
            <template v-if="row.isEdit">
              <el-switch
                v-model="editForm.state"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
            <!-- 使用作用域插槽 -->
            <template v-else>
              {{ row.state == 1?'已启用':'未启用' }}
              {{ row.isEdit }}
            </template>
          </el-table-column>
          <el-table-column
            v-slot="{row}"
            prop="description"
            label="描述"
            align="center"
          >
            <template v-if="row.isEdit">
              <el-input v-model="editForm.description" type="textarea" />
            </template>
            <template v-else>
              {{ row.description }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="667px"
            align="center"
          >
            <template v-slot="{row}">
              <template v-if="row.isEdit">
                <el-button type="primary" @click="editSubmit">确定</el-button>
                <el-button @click="row.isEdit = false">取消</el-button>
              </template>
              <template v-else>
                <el-button type="text" size="small" @click="assignPermisionTmp(row.id)">分配权限</el-button>
                <el-button type="text" size="small" @click="updateRoeTmp(row)">编辑</el-button>
                <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @onConfirm="popconfirm(row.id)"
                >
                  <el-button slot="reference" style="margin-left: 10px;" type="text" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="rc-3">
        <el-pagination
          layout="total, prev, pager, next"
          :total="total"
          :current-page="form.page"
          :page-size="form.pagesize"
          @current-change="handleCurrentChange"
        />
        <!-- 当前页码值和每页显示多少条数据，点击切换时的回调函数 -->
      </div>

      <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="close">
        <el-form ref="formDateRef" :model="addForm" :rules="addFormRules">
          <el-form-item label="角色名称：" label-width="120px" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="启用：" label-width="120px" prop="newPassword">
            <el-switch
              v-model="addForm.state"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述：" label-width="120px" prop="description">
            <el-input v-model="addForm.description" type="textarea" />
          </el-form-item>
          <el-form-item label-width="120px">
            <el-button type="primary" @click="doAdd">确认</el-button>
            <el-button @click="showDialog = false">取 消</el-button>
          </el-form-item>
        </el-form>

      </el-dialog>
      <!-- 给角色分配权限的弹出框 -->
      <!--因为dialog只是隐藏了dom结构还存在，所以会出现数据残留的问题 凡是涉及到dialog弹窗数据残留问题，
        利用v-if直接清除dom元素 -->
      <el-dialog
        v-if="dialogVisible"
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <span>这是一段信息</span>
        <el-tree ref="treeRef" show-checkbox default-expand-all :data="treeList" node-key="id" :props="{label: 'name', children: 'children'}" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignPermisionSubmitTmp">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { sysRoleListRequest, addRoleListRequest, deleteRoleListRequest,
  upadteRoleListRequest, getRoleDetailRequest, assignPremRequest } from '@/api/role'
import { sysPermissionListRequest } from '@/api/permission'
import { transformListToTree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      form: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      showDialog: false,
      addForm: {
        name: '',
        state: 1,
        description: ''
      },
      editForm: {
        name: '',
        state: 1,
        description: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      treeList: [],
      currentRoleId: null
    }
  },
  created() {
    this.sysRoleList()
  },
  methods: {
    // 渲染列表
    async sysRoleList() {
      const res = await sysRoleListRequest(this.form)
      // console.log(res)
      this.roleList = res.data.rows
      this.total = res.data.total
      // 给每一个对象添加isEdit属性，用来控制每一行是否是在编辑状态还是数据显示状态
      // vue的数据响应式的发生变化，在最开始的时候，数据只有绑定在data上面，才能被vue的底层方法
      // Object.defineproperty(obj,'total',{get(){},set(){}})递归进行，响应式数据的get set的转化劫持
      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)
      })
    },
    // 换页时候调用函数
    handleCurrentChange(val) {
      this.form.page = val
      this.sysRoleList()
    },
    addRole() {
      this.showDialog = true
    },
    // 关弹窗事件 里面可能有多个事件，表单重置啊
    close() {
      this.showDialog = false
      this.$refs.formDateRef.resetFields()
    },
    doAdd() {
      this.$refs.formDateRef.validate(async(valid) => {
        if (valid) {
          await addRoleListRequest(this.addForm)
          this.close()
          this.$message.success('新增角色成功！')
          this.sysRoleList()
        }
      })
    },
    // 删除
    async popconfirm(id) {
      console.log(id)
      await deleteRoleListRequest(id)
      this.$message.success('删除成功！')
      this.sysRoleList()
    },
    updateRoeTmp(type) {
    // 做一个排他思想，将其他的已经打开的关闭
      // eslint-disable-next-line no-return-assign
      this.roleList.forEach(item => item.isEdit = false)
      type.isEdit = true
      // 这个操作是把每一行的数据给回显，每一行的数据给新添加的每一个元素
      this.editForm = { ...type }
    },
    async editSubmit() {
      await upadteRoleListRequest(this.editForm)
      this.$message.success('更新成功！')
      this.sysRoleList()
    },
    assignPermisionTmp(id) {
      this.currentRoleId = id
      this.dialogVisible = true
      this.getPermissionList()
    },
    async getPermissionList() {
      // 这是树形组件的渲染
      const res = await sysPermissionListRequest()
      this.treeList = transformListToTree(res.data, 0)
      // 这个请求是请求回显的数据的
      const res1 = await getRoleDetailRequest(this.currentRoleId)
      // 这是权限数据回显
      this.$refs.treeRef.setCheckedKeys(res1.data.permIds)
    },
    async assignPermisionSubmitTmp() {
      this.dialogVisible = false
      // 获取被复选框被选择的id
      // console.log(this.$refs.treeRef.getCheckedKeys())
      await assignPremRequest({
        id: this.currentRoleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.dialogVisible = false
      this.sysRoleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.role-container{
  padding:10px ;
  font-size: 14px;
  min-height: calc(100vh - 80px);
  background-color: #f5f6f8;
  .box{
    background-color: #fff;
    .rc-1{
      padding: 10px;
    }
    .rc-2{
      margin: 20px 0;
    }
    .rc-3{
      text-align: right;
    }
    ::v-deep .el-input__inner{
      height: 28px;
    }
    ::v-deep .el-textarea__inner{
      height: 66px;
    }
  }
}

</style>
